package com.pluszg.nutrition.common.utils;

import lombok.NoArgsConstructor;

import java.util.Random;
import java.util.UUID;
import java.util.stream.IntStream;

import static java.util.stream.Collectors.joining;
import static lombok.AccessLevel.PRIVATE;

@NoArgsConstructor(access = PRIVATE)
public class RandomUtil {

    public static final String[] chars = new String[]{"a", "b", "c", "d", "e", "f",
            "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z"};

    /**
     * 生成32位uuid 不带-
     *
     * @return
     */
    public static String generateUUID() {
        return generateStandardUUID().replace("-", "");
    }

    /**
     * 生成32位标准uuid 即带-
     *
     * @return
     */
    public static String generateStandardUUID() {
        return UUID.randomUUID().toString();
    }

    /**
     * 生成8位短uuid
     *
     * @return
     */
    public static String generateShortUUID() {
        return IntStream.range(0, 8)
                .mapToObj(i -> NumberUtil.hex2Ten(generateUUID().substring(i * 4, i * 4 + 4)))
                .map(x -> chars[x % 0x3E]).collect(joining());
    }

    public static String getRandNum(int charCount) {
        Assert.isTrue(charCount > 0, "随机数长度应大于0");
        return IntStream.range(0, charCount)
                .mapToObj(i -> "" + randomInt(0, 10))
                .collect(joining());
    }

    public static int randomInt(int from, int to) {
        Random r = new Random();
        return from + r.nextInt(to - from);
    }

    public static String randomStr(int length) {
        Assert.isTrue(length > 0, "随机字符串长度应大于0");
        Random random = new Random();
        return IntStream.range(0, length)
                .map(i -> random.nextInt(chars.length))
                .mapToObj(number -> chars[number])
                .collect(joining());
    }

    public static byte[] int2Bytes(int count) {
        return new byte[]{(byte) (count >> 24 & 255), (byte) (count >> 16 & 255), (byte) (count >> 8 & 255), (byte) (count & 255)};
    }

    public static int bytes2int(byte[] byteArr) {
        int count = 0;

        for (int i = 0; i < 4; ++i) {
            count <<= 8;
            count |= byteArr[i] & 255;
        }

        return count;
    }
}
